import { t } from '@src/locales'
/* Api */
import * as TaskApi from '@src/api/TaskApi'
/* component */
import BizTable from '@src/component/business/BizTable/BizTable.tsx'
import BizLogisticsNo from '@src/component/business/BizLogisticsNo'
/* config */
import PaymentConfig from '@model/config/PaymentConfig'
/* enum */
import AuthValueEnum from '@model/enum/AuthValueEnum'
import ComponentNameEnum from '@model/enum/ComponentNameEnum'
import { FieldTypeMappingEnum, TaskFieldNameMappingEnum } from '@model/enum/FieldMappingEnum'
import TaskStateEnum from '@model/enum/TaskStateEnum'
import BalanceConfirmEnum from '@model/enum/BalanceConfirmEnum'
import StorageModuleEnum from '@model/enum/StorageModuleEnum'
import AuthEnum from '@model/enum/AuthEnum'
/* entity */
import EsTask from '@model/entity/EsTask'
import EsTaskLoginUser from '@model/entity/EsTaskLoginUser'
import LoginUser from '@model/entity/LoginUser/LoginUser'
import TaskAddress from '@model/entity/TaskAddress'
import { PlanTask } from '@model/entity/PlanTask'
/* filter */
import { fmt_datetime, fmt_number_fixed2, fmt_seconds_to_hour_str, fmt_currency_fixed2 } from '@src/filter/fmt'
import {fmt_form_cascader, fmt_currency, fmt_form_address, fmt_richtext} from '@src/filter/form'
/* model */
import { OpenDataToolTip } from '@model/types/OpenData'
/* vue */
import { Component, Prop, Mixins } from 'vue-property-decorator'
import { VNode } from 'vue/types/vnode'
/* scss */
import '@src/component/business/BizTable/BizTable.scss'
/* service */
import { getTaskId, isTaskManager } from '@service/TaskService'
import { formattedOpenDataTooltip } from '@service/OpenDataService'
/* types */
import Column from '@model/types/Column'
/* util */
import { openTabForCustomerView, openTabForTaskView, openTabForUserView, openTabForEventView } from '@src/util/business/openTab'
import Log from '@src/util/log.ts'
import { isArray, isEmpty } from '@src/util/type'
import { storageGet, storageSet } from '@src/util/storage.ts'
import { getFieldName, isSystemFiled } from '@service/FieldService'
import { fieldArrayToObject, FieldArrayToObjectKeyEnum } from '@src/util/array'
import { strConcat as concat, formatDate } from 'pub-bbx-utils'
import { isOpenData } from '@src/util/platform'
import { safeNewDate } from '@src/util/time';
import LogisticsMixin from '@src/mixins/logisticsMixin'


export type BizTableTaskScopeSlot = {
  column: Column,
  value: EsTask
}

// 派单方式 数据转换
const AllotTypeConvertMap: { [x: string]: number } = {
  [t('common.base.all')]: 0,
  [t('task.detail.components.manualDispatch')]: 1,
  [t('task.detail.components.poolDispatch')]: 2,
  [t('task.detail.components.autoDispatch')]: 3
}

/* 工单 曾.. 字段名称列表 */
const TaskOnceFieldNames: string[] = [
  TaskFieldNameMappingEnum.OnceOverTime,
  TaskFieldNameMappingEnum.OncePaused,
  TaskFieldNameMappingEnum.OnceRefused,
  TaskFieldNameMappingEnum.OnceRollback,
  TaskFieldNameMappingEnum.OnceReallot,
  TaskFieldNameMappingEnum.OncePrinted,
  TaskFieldNameMappingEnum.PositionException,
]

const ElementTableBodyClassName: string = '.el-table__body-wrapper'

function displaySelect(value: any): string | null {
  if (!value) return null
  if (value && typeof value === 'string') {
    return value
  }
  if (Array.isArray(value) && value.length) {
    return value.join('，')
  }
  return null
}

@Component({
  name: ComponentNameEnum.BizTableTask,
  mixins: [LogisticsMixin]
})
class BizTableTask extends BizTable {
  
  /* 权限数据 */
  @Prop() readonly auth: Record<AuthEnum | string, number> | undefined
  /* 支付设置信息 */
  @Prop({ default: () => ({}) }) readonly paymentConfig: PaymentConfig | undefined
  
  private isOpenData: boolean = isOpenData
  
  /* 是否允许工单编辑 */
  get allowTaskEdit(): boolean {
    return this.auth?.TASK_EDIT === AuthValueEnum.All
  }
  
  /**
   * @description: 是否允许查看工单详情
   * @return {boolean}
   */
  get allowTaskViewDetail(): boolean {
    return Boolean(this.auth?.[AuthEnum.TASK_VIEW_DETAIL])
  }
  
  get isTaskManager(): boolean {
    return isTaskManager(this.auth || {})
  }
  
  get taskTableFieldsMap(): Record<string, EsTask>{
    const taskTableFields: EsTask[] = this.data || []
    return fieldArrayToObject<EsTask>(taskTableFields, FieldArrayToObjectKeyEnum.Id)
  }
  
  /**
   * @description 获取显示最后一次更新记录
   * @param {Object} row 行数据
   */
  async fetchLastUpdateRecord(row: EsTask) {
    // 存在历史更新记录
    if (row.lastUpdateRecord) {
      return console.warn(`Caused: ${row.taskNo} row have lastUpdateRecord`)
    }
    
    try {
      const result = await TaskApi.getTaskUpdateRecord({ taskId: row.id })
      const { succ, data } = result
      
      if (!succ) return
      // @ts-ignore
      this.data.forEach((item) => {
        if (item.id === row.id) {
          // 通过set方法更新表格 '最近更新' 列的数据，触发视图更新
          // reRenderTable 方法 重新渲染表格的方式会导致表格更新时，选中状态消失。所以注释了。
          // @ts-ignore 
          this.$set(item, 'lastUpdateRecord', data)
        }
      })
      // 更新工单上的最后更新时间数据
      // this.taskTableFieldsMap[getTaskId(row)].lastUpdateRecord = data
      
      // 重新渲染表格以显示提示 (暂时先用这么蠢的办法)
      const ElementBodyHtmlElement: Element | Record<string, any> = this.$el.querySelector(ElementTableBodyClassName) || {}
      const ElementBodyHtmlElementScrollLeft = ElementBodyHtmlElement.scrollLeft
      
      // this.reRenderTable()
      this.$nextTick(() => {
        // @ts-ignore
        this.$el.querySelector(ElementTableBodyClassName).scrollLeft = ElementBodyHtmlElementScrollLeft
      })
    
    } catch (error) {
      Log.error(error, `${ComponentNameEnum.BizTableTask} -> ${this.fetchLastUpdateRecord.name}`)
    }
  }
  
  /**
    * @description 派单方式文案
  */
  private getAllotTypeText(allotType: number): string {
    for(let key in AllotTypeConvertMap) {
      let value = AllotTypeConvertMap[key]
      if (value == allotType) return key
    }
    
    return t('common.base.all')
  }
  
  /**
   * @description 从缓存获取数据
  */
  public async getDataToStorage(key: string, data: any) {
    return storageGet(key, data, StorageModuleEnum.Task)
  }
  
  /**
   * @description 打开客户详情
   * @param {object} customerInfo 客户详情
  */
  private openCustomerViewTab(customerInfo: any) {
    const { linkAuth, customerEntity } = customerInfo
    // 没有查看权限
    if (!linkAuth) return
    
    // 打开客户详情tab
    const { id } = customerEntity
    openTabForCustomerView(id)
  }
  
  /**
   * @description 保存数据到缓存
  */
  public saveDataToStorage(key: string, data: any) {
    storageSet(key, data, StorageModuleEnum.Task)
  }
  
  /**
   * @description: 渲染业务列
   * @param {Column} column 列数据
   * @param {EsTask} row 行数据
   * @return {VNode | null} 
  */  
  public renderColumnWithBusiness(column: Column, row: EsTask) {
    // 字段名称
    // 国际货币
    if (column.formType === FieldTypeMappingEnum.Currency) return this.renderColumnWithCurrency(column, row)
    // 物流组件信息
    if (column.formType === TaskFieldNameMappingEnum.Logistics) {
      return this.renderColumnWithLogistics(column, row)
    }
    const fieldName = getFieldName(column)
    // 客户产品关联字段
    if (column.formType === FieldTypeMappingEnum.RelatedCustomer || column.formType === FieldTypeMappingEnum.RelatedProduct) return this.renderColumnWithRelatedCustomer(column, row)
     // 创建人或负责人
    if (
      fieldName === TaskFieldNameMappingEnum.CreateUserName
      || fieldName === TaskFieldNameMappingEnum.ExecutorName
      || fieldName === TaskFieldNameMappingEnum.AllotName
      || fieldName === TaskFieldNameMappingEnum.BalanceUser
    ) return this.renderColumnWithBusinessUser(column, row)
    // 被指派人
    if (fieldName === FieldTypeMappingEnum.TaskUserName ) return this.renderColumnWithTaskUserName(column, row)
    // 协同人
    if (fieldName === TaskFieldNameMappingEnum.Synergies) return this.renderColumnWithSynergies(column, row)
     // 人员
    if (column?.formType === FieldTypeMappingEnum.User) return this.renderColumnWithUser(column, row)
    // 自定义的选择类型字段显示， 与type 区别
    if (column?.formType === FieldTypeMappingEnum.Select && !column.isSystem && !column?.isBalanceField) return this.renderColumnWithAttributeSelect(column, row)
    // 关联工单
    if (column.formType === FieldTypeMappingEnum.RelatedTask) return this.renderColumnWithRelatedTask(column, row)
    // 非系统字段
    if (!column.isSystem) return this.renderColumnWithNotSystem(column, row)

  
    // 工单编号
    if (fieldName === TaskFieldNameMappingEnum.TaskNo) return this.renderColumnWithTaskNo(column, row)
    // 客户
    if (fieldName === TaskFieldNameMappingEnum.Customer) return this.renderColumnWithCustomer(column, row)
    // 关联事件
    if (fieldName === TaskFieldNameMappingEnum.EventNo) return this.renderColumnWithEventNo(column, row)
    // 联系人名称
    if (fieldName === TaskFieldNameMappingEnum.TlmName) return this.renderColumnWithTlmName(column, row)
    // 联系人手机号码
    if (fieldName === TaskFieldNameMappingEnum.TlmPhone) return this.renderColumnWithTlmPhone(column, row)
    // 更新时间
    if (fieldName === TaskFieldNameMappingEnum.UpdateTime) return this.renderColumnWithUpdateTime(column, row)
    // 计划时间
    if (fieldName === TaskFieldNameMappingEnum.PlanTime) return this.renderColumnWithPlanTime(column, row)
    // 产品
    if (fieldName === TaskFieldNameMappingEnum.Product) return this.renderColumnWithProduct(column, row)
    // 派单方式
    if (fieldName === TaskFieldNameMappingEnum.AllotTypeStr) return this.renderColumnWithAllotTypeStr(column, row)
    // 负责人团队
    if (fieldName === TaskFieldNameMappingEnum.ExecutorTags) return this.renderColumnWithExecutorTags(column, row)
    // 审批状态
    if (fieldName === TaskFieldNameMappingEnum.InApprove) return this.renderColumnWithInApprove(column, row)
    // 状态
    if (fieldName === TaskFieldNameMappingEnum.State) return this.renderColumnWithState(column, row)
    // 结算状态
    if (fieldName === TaskFieldNameMappingEnum.BalanceConfirm) return this.renderColumnWithBalanceState(column, row)
    // 接单用时
    if (fieldName === TaskFieldNameMappingEnum.AcceptUsedTimeStr) return this.renderColumnWithAcceptedUsedTime(column, row)
    // 工单用时
    if (fieldName === TaskFieldNameMappingEnum.TaskUsedTimeStr) return this.renderColumnWithTaskUsedTime(column, row)
    // 工作用时
    if (fieldName === TaskFieldNameMappingEnum.WorkUsedTimeStr) return this.renderColumnWithWorkUsedTime(column, row)
    // 工单响应时间
    if (fieldName === TaskFieldNameMappingEnum.TaskResponseTimeStr) return this.renderColumnWithTaskResponseTime(column, row)
    // 备件费用
    if (fieldName === TaskFieldNameMappingEnum.SparePartsPrice) return this.renderColumnWithSparePartPrice(column, row)
    // 服务费用
    if (fieldName === TaskFieldNameMappingEnum.ServicePartsPrice) return this.renderColumnWithServicePartsPrice(column, row)
    // 折扣费用
    if (fieldName === TaskFieldNameMappingEnum.Discount) return this.renderColumnWithDiscount(column, row)
    // 合计费用
    if (fieldName === TaskFieldNameMappingEnum.TotalPrice) return this.renderColumnWithTotalPrice(column, row)
    // 成本
    if (fieldName === TaskFieldNameMappingEnum.TotalCost) return this.renderColumnWithCost(column, row)
    // 毛利
    if (fieldName === TaskFieldNameMappingEnum.TotalProfit) return this.renderColumnWithProfit(column, row)
    // 结算操作
    if (fieldName === TaskFieldNameMappingEnum.BalanceOperation) return this.renderColumnWithBalanceOperation(column, row)
    // 已创建工单
    if (fieldName === TaskFieldNameMappingEnum.CreatedTasks) return this.renderColumnWithCreateTasks(column, row as unknown as PlanTask)
    // 支付方式
    if (
      column.field === TaskFieldNameMappingEnum.PaymentMethod
      && this.paymentConfig?.version === 1
    ) return this.renderColumnWithPaymentMethod(column, row)
    // 曾...字段
    if (TaskOnceFieldNames.indexOf(fieldName) > -1) return this.renderColumnWithOnceField(column, row)
    // 地址
    if (column?.formType === FieldTypeMappingEnum.Address) return this.renderColumnWithAddress(column, row)
    
    // 位置
    if (column?.formType === FieldTypeMappingEnum.Location) return this.renderColumnWithLocation(column, row)
    // 日期
    if (column?.formType === FieldTypeMappingEnum.DateTime) return this.renderColumnWithDateTime(column, row)
    // 文本
    if (column.formType === FieldTypeMappingEnum.Textarea) return this.renderColumnWithTextarea(column, row)
    // 多级菜单
    if (column.formType === FieldTypeMappingEnum.Cascader) return this.renderColumnWithCascader(column, row)
    
    return this.renderColumnWithCommon(column, row)
  }
  
  /* 客户产品关联字段 */
  private renderColumnWithRelatedCustomer(column: any, row: EsTask): VNode {
    if(isOpenData && (column?.setting?.formType === 'user' || column?.setting?.fieldName === 'customerManager')) {
      let value = row?.attribute?.[column.field]
      if(!value) return this.renderColumnWithCommon(column, row)
      if(column?.setting?.formType === 'user') {
        const staffIds = value.split(',') || []
        return (
          <div>{ staffIds.length && staffIds.map((i: any) =><open-data type="userName" openid={i}></open-data>) }</div> 
        )
      }
      // 客户负责人
      return ( 
        <div>
          { value && <open-data type="userName" openid={value}></open-data> }
        </div> 
      )
    }
    
    const {isMulti, displayMode, formType, module} = column?.setting || {};
    if(formType === 'cascader') {
      const value = row?.attribute?.[column.field];
      let data = '';
      if (column.tableName !== 'register' && formType === 'cascader') {
        if (module === 'product') {
          data = (value || []).map((item: any) => fmt_form_cascader(item, isMulti)).join('、')
        } else {
          data = fmt_form_cascader(value, isMulti, displayMode)
        }
      }
      return (
        <div>{ data }</div> 
      )
    }
    return this.renderColumnWithCommon(column, row)
  }

  /* 渲染工单编号 */
  private renderColumnWithTaskNo(column: Column, row: EsTask) {
    // 是否超时
    const IsOverTime = row.overTime && safeNewDate().getTime() > row.overTime.getTime()
    
    return (
      // superscript 为 示例数据的标签
      <div class={{ superscript: row.guideData }}>
        <div 
          class={this.allowTaskViewDetail ? 'view-detail-btn task-list-numbering' : 'view-detail-btn-disabled task-list-numbering'}
          onClick={() => {
            
            if (!this.allowTaskViewDetail) return
            
            openTabForTaskView(getTaskId(row) || '')
          }}
        >
          { this.getValue(column.field, row) }
        </div>
        {
          row.inApprove && (
            <span class='task-state-block task-state-block-approve task-font12'>
              {t('common.task.approveStatus.approve')}
            </span>
          )
        }
        {
          IsOverTime && (
            <span class='task-state-block task-state-block-overtime task-font12'>
              {t('common.task.exceptionStatus.overTime')}
            </span>
          )
        }
      </div>
    )
  }

  /* 渲染物流信息 */
  private  renderColumnWithLogistics(column: Column, row: EsTask) {
    return (
      <biz-list-logistics-no
        row={row}
        column={column}
        // @ts-ignore
        is-link={this.isCanLogisticsNoLink(column)}
        mode="task"
        biz-id={row.id}
      />
    )
  }
  /* 客户 */
  private renderColumnWithCustomer(column: Column, row: EsTask) {
    const classNames = row.linkAuth ? 'view-detail-btn task-client' : ''
    
    return (
      <div
        class={classNames}
        onClick={ () => this.openCustomerViewTab(row) }
      >
        { row?.customerEntity?.name }
      </div>
    )
  }
  
  /* 事件编号 */
  private renderColumnWithEventNo(column: Column, row: EsTask) {
    const eventId: string = row?.eventId || ''
    
    return (
      <div class='view-detail-btn task-client' onClick={() => openTabForEventView(eventId)}>
        { row?.[column.field || ''] }
      </div>
    )
  }
  
  /* 联系人 */
  private renderColumnWithTlmName(column: Column, row: EsTask) {
    return (
      <div>
        { row?.linkMan?.name }
      </div>
    )
  }
  
  /* 联系人电话 */
  private renderColumnWithTlmPhone(column: Column, row: EsTask) {
    return (
      <div>
        { row?.linkMan?.phone }
      </div>
    )
  }
  
  /* 自定义的选择类型字段显示， 与type 区别 */
  private renderColumnWithAttributeSelect(column: Column, row: EsTask) {
    return (
      <div>
        { displaySelect(row?.attribute?.[column.field || '']) }
      </div>
    )
  }
  
  /* 更新时间 */
  private renderColumnWithUpdateTime(column: Column, row: EsTask) {
    const IsHaveUpdateRecord: boolean = Boolean(row.lastUpdateRecord)
    
    // 没有更新日志
    if (!IsHaveUpdateRecord || isOpenData) {
      return (
        <div onMouseover={() => this.fetchLastUpdateRecord(row) }>
          { fmt_datetime(row.updateTime) }
        </div>
      )
    }
    
    const openDataToolTipList: OpenDataToolTip[] = formattedOpenDataTooltip(row.lastUpdateRecord || '')
    const openDataToolTipListElement = openDataToolTipList.map(openDataToolTip => {
      if (openDataToolTip.text) {
        return <span>{openDataToolTip.text}</span>
      }
      if (openDataToolTip.staffId && this.isOpenData) {
        return <open-data type="userName" openid={openDataToolTip.staffId}></open-data>
      }
      if (openDataToolTip.userName) {
        return <span>{openDataToolTip.userName}</span>
      }
    })
    
    // 有更新日志
    return (
      <el-tooltip
        class='item'
        effect='dark'
        placement='top'
      >
        <div slot="content">
          { openDataToolTipListElement }
        </div>
        <div>
          { fmt_datetime(row.updateTime) }
        </div>
      </el-tooltip>
    )
  }
  
  /* 计划时间 */
  private renderColumnWithPlanTime(column: Column, row: EsTask) {
    return row?.isEncryptPlanTime ? '***' : row[getFieldName(column)]
  }
  
  /* 产品 */
  private renderColumnWithProduct(column: Column, row: EsTask) {
    return (
      row?.products ? concat(row.products.map((product: any) => product.name)) : null
    )
  }
  
  /* 创建人 或 负责人 或 派单人 或 结算人 */
  private renderColumnWithBusinessUser(column: Column, row: EsTask): VNode | string {
    // 用户信息
    let user: EsTaskLoginUser | null | undefined = null
    // 字段名称
    const FieldName = getFieldName(column)
    
    // 创建人
    if (FieldName === TaskFieldNameMappingEnum.CreateUserName) {
      user = row?.createUser
    }
    // 负责人
    else if (FieldName === TaskFieldNameMappingEnum.ExecutorName) {
      user = row?.executorUser
    }
    // 派单人
    else if (FieldName === TaskFieldNameMappingEnum.AllotName) {
      user = row?.allotUser
    }
    // 结算人
    else if (FieldName === TaskFieldNameMappingEnum.BalanceUser) {
      user = row?.balanceUser
    }
    
    // 查看工单全部权限 可点击链接跳转
    const AllowView: boolean = this.isTaskManager
    // 用户id
    const UserId: string = user?.userId || ''
    // 用户名称
    const DisplayName: string = user?.displayName || ''
    
    // 不支持链接查看
    if (!AllowView) {
      if(isOpenData) {
        return (<span><open-data type="userName" openid={user?.staffId}></open-data></span>)
      }
      return DisplayName
    }
    
    // 支持跳转
    if(isOpenData) {
      return (
        <div class='view-detail-btn view-user-detail-btn' onClick={() => openTabForUserView(UserId)}>
          <open-data type="userName" openid={user?.staffId}></open-data>
        </div>
      )
    }
    return (
      <div class='view-detail-btn view-user-detail-btn' onClick={() => openTabForUserView(UserId)}>
        { DisplayName }
      </div>
    )
  }
  
  /* 被指派人 */
  private renderColumnWithTaskUserName(column: Column, row: EsTask) {
    const DisplayName = row[column?.fieldName || ''] || []

    // 查看工单全部权限 可点击链接跳转
    const AllowView: boolean = this.isTaskManager
    // 不支持链接查看
    if (!AllowView) {
      return DisplayName
    }
    return (
      <div class='view-detail-btn view-user-detail-btn' onClick={() => openTabForUserView(row?.taskUserId)}>
        { DisplayName }
      </div>
    )
  }
  /* 协同人 */
  private renderColumnWithSynergies(column: Column, row: EsTask) {
    const SynergiesUsers = row[column?.field || ''] || []
    if(isOpenData) {
      return (
        SynergiesUsers.map((synergiesUser: any) => <open-data v type="userName" openid={synergiesUser?.staffId}></open-data>)
      )
    }
    return (
      concat(SynergiesUsers.map((synergiesUser: any) => synergiesUser.displayName))
    )
  }

  /* 派单方式 */
  private renderColumnWithAllotTypeStr(column: Column, row: EsTask) {
    return this.getAllotTypeText(Number(row.allotType))
  }
  
  /* 负责人团队 */
  private renderColumnWithExecutorTags(column: Column, row: EsTask) {
    const fieldName: string = column.field || ''
    const value: any[] = row[fieldName] || []
    
    if (!isArray(value)) return ''
    
    return concat(value.map(item => item?.name), '、')
  }
  
  /* 审批状态 */
  private renderColumnWithInApprove(column: Column, row: EsTask) {
    const fieldName: string = column.field || ''
    const value: number | undefined = row?.[fieldName]
    return value == 0 ? t('common.task.approveStatus.noApprove') : t('common.task.approveStatus.approve')
  }
  
  /* 工单状态 */
  private renderColumnWithState(column: Column, row: EsTask) {
    // 是否暂停中
    const IsPaused = row.isPaused == 1
    // 暂停中
    if (IsPaused){
      return (
        <div
          class='task-state-block task-font12 table-blacklist'
          style='color: rgba(153, 153, 153);background-color: rgba(153, 153, 153, .2)'
        >
          {t('common.task.status.paused')}
        </div>
      )
    }
    
    const state: string = row[column?.field || '']
    return (
      <div
        class='task-state-block task-font12 table-blacklist'
        style={{
          backgroundColor: TaskStateEnum.getBgColor(state, 1),
          color: '#FFF'
        }}
      >
        { state && TaskStateEnum.getName(state) }
      </div>
    )
  }
  
  /* 结算状态 */
  private renderColumnWithBalanceState(column: Column, row: EsTask) {
    // 结算状态
    const state: number = row[column?.field || '']
    const balanceStateMap: { [x: number]: Record<string, any> } = {
      // 已结算
      1: {
        borderColor: '#ff9933',
        backgroundColor: '#ff9933',
        text: t('common.task.status.settled')
      },
      // 未结算
      0: {
        borderColor: '#ffb966',
        backgroundColor: '#ffb966',
        text: t('common.task.status.unBalanced')
      }
    }
    
    return (
      <div
        class='task-state-block task-font12 table-blacklist'
        style={{
          backgroundColor: balanceStateMap[state]?.backgroundColor,
          color: '#fff',
          border: `1px solid ${balanceStateMap[state]?.borderColor}`,
        }}
      >
        { balanceStateMap[state]?.text }
      </div>
    )
  }
  
  /* 备件费用 */
  private renderColumnWithSparePartPrice(column: Column, row: EsTask) {
    const balanceEntity = row.balanceEntity || {}
    const sparePartsPrice = balanceEntity.sparePartsPrice || 0
    const settlementCurrency = balanceEntity.settlementCurrency || 'CNY'
    
    return (
      <div>{ fmt_currency_fixed2(sparePartsPrice, settlementCurrency) } </div>
    )
  }
  
  /* 服务费用 */
  private renderColumnWithServicePartsPrice(column: Column, row: EsTask) {
    const balanceEntity = row.balanceEntity || {}
    const servicePartsPrice = balanceEntity.servicePartsPrice || 0
    const settlementCurrency = balanceEntity.settlementCurrency || 'CNY'

    return (
      <div>{ fmt_currency_fixed2(servicePartsPrice, settlementCurrency) }</div>
    )
  }
  
  /* 折扣费用 */
  private renderColumnWithDiscount(column: Column, row: EsTask) {
    const balanceEntity = row.balanceEntity || {}
    const discount = balanceEntity.discount || 0
    const settlementCurrency = balanceEntity.settlementCurrency || 'CNY'
    return (
      <div>{ fmt_currency_fixed2(discount, settlementCurrency) }</div>
    )
  }
  
  /* 合计费用 */
  private renderColumnWithTotalPrice(column: Column, row: EsTask) {
    const balanceEntity = row.balanceEntity || {}
    const totalPrice = balanceEntity.totalPrice || 0
    const settlementCurrency = balanceEntity.settlementCurrency || 'CNY'
    return (
      <div>{ fmt_currency_fixed2(totalPrice, settlementCurrency) }</div>
    )
  }
  
  /* 成本 */
  private renderColumnWithCost(column: Column, row: EsTask) {
    const balanceEntity = row.balanceEntity || {}
    const totalCost = balanceEntity.totalCost
    const totalCostCurrency = balanceEntity.totalCostCurrency || 'CNY'
    
    return (
      <div>{ fmt_currency_fixed2(totalCost, totalCostCurrency) }</div>
    )
  }
  
  /* 毛利 */
  private renderColumnWithProfit(column: Column, row: EsTask) {
    const balanceEntity = row.balanceEntity || {}
    const totalProfit = balanceEntity.totalProfit
    const settlementCurrency = balanceEntity.settlementCurrency || 'CNY'

    return (
      <div>{ fmt_currency_fixed2(totalProfit, settlementCurrency) }</div>
    )
  }
  
  /* 结算操作 */
  private renderColumnWithBalanceOperation(column: Column, row: EsTask) {
    // 是否结算
    const isBalanced: boolean = row.balanceConfirm == BalanceConfirmEnum.BalanceConfirm
    // 工单id
    const taskId: string = row.id
    
    return (
      <el-button type='text' onClick={() => openTabForTaskView(taskId, true, true)}>
        { isBalanced ? t('common.base.view') : t('common.base.settleAccounts') }
      </el-button>
    )
    
  }
  
  /* 已创建工单 */
  private renderColumnWithCreateTasks(column: Column, row: PlanTask) {
    const createTasks  = row?.createdTasks || []
    const isCreatedTasksEmpty = isEmpty(createTasks)
    
    return (
      <el-tooltip
        class='item'
        effect='dark'
        placement='top'
      >
        {!isCreatedTasksEmpty && (
          <div slot="content">
            {
              createTasks.map(task => (
                <div>
                  {t('common.form.type.taskNo')}: {task?.taskNo || ''}
                  &nbsp;&nbsp;
                  {t('common.fields.createTime.displayName')} {formatDate(safeNewDate(task?.createTime)) || ''}
                </div>
              ))
            }
          </div>
        )}
        <div>
        { isCreatedTasksEmpty ? '' : createTasks.length }
        </div>
      </el-tooltip>
    )
  }
  
  /* 多行文本 */
  private renderColumnWithTextarea(column: Column, row: EsTask): VNode {
    const value: string = row?.attribute?.[column.field || ''] || ''
    
    return ( 
      <div onClick={(event: any) => this.openOutsideLink(event) }>
        { this.buildTextarea(value) }
      </div> 
    )
  }
  
  /* 多级菜单 */
  private renderColumnWithCascader(column: Column, row: EsTask): VNode {
    const value: string = row?.attribute?.[column.field || ''] || ''
    
    return ( 
      <div>
        { fmt_form_cascader(value, column.setting?.isMulti, column.setting?.displayMode) }
      </div> 
    )
  }
  
  /* 国际货币 */
  private renderColumnWithCurrency(column: Column, row: EsTask): VNode {
    const value: object = row?.attribute?.[column.field || ''] || {}
    
    return ( 
      <div>
        { fmt_currency(value) }
      </div> 
    )
  }
  
  /* 关联工单 */
  private renderColumnWithRelatedTask(column: Column, row: EsTask): VNode {
    const value: EsTask[] = row?.attribute?.[column.field || ''] || []
    
    return (
      <div class='related-task-item'>
        {
          value.map((task: EsTask, index: number) => {
            return (
              <div class='link-text' onClick={() => openTabForTaskView(getTaskId(task))}>
                { task?.taskNo }
                <span class='related-task-item-separator'>{ index < value.length - 1 && ', '}</span>
              </div>
            )
          })
        }
      </div> 
    )
  }
  
  /* 曾..字段 */
  private renderColumnWithOnceField(column: Column, row: EsTask) {
    return Number(row[column.field || '']) === 1 ? t('common.base.yes') : t('common.base.no')
  }
  
  /* 地址类型 */
  private renderColumnWithAddress(column: Column, row: EsTask): string {
    const address: any = row?.[column.formType || ''] || {}
    return new TaskAddress(address).toString()
  }
  
  /* 人员类型 */
  private renderColumnWithUser(column: Column, row: EsTask): any {
    
    const user: LoginUser | any = row?.attribute?.[column.field || ''] || {}
    
    // 单选人员
    if(isOpenData && user.staffId) {
      return (<span><open-data type="userName" openid={user.staffId}></open-data></span>)
    }
    // 多选人员
    if (isOpenData && isArray(user)) {
      return (
        user.map((item: LoginUser) => {
          return <open-data type="userName" openid={item.staffId}></open-data>
        })
      )
    }
    
    return user?.displayName || user?.name || ''
  }
  
  /* 位置类型 */
  private renderColumnWithLocation(column: Column, row: EsTask): string {
    const location: any = row?.attribute?.[column.field || ''] || {}
    return location?.address || ''
  }
  
  /* 日期类型 */
  private renderColumnWithDateTime(column: Column, row: EsTask): string {
    const fieldName: string = column.field || ''
    const isSystem: boolean = isSystemFiled(column)
    
    return isSystem ? fmt_datetime(row?.[fieldName]) : fmt_datetime(row?.attribute?.[fieldName])
  }
  
  /* 接单用时 */
  private renderColumnWithAcceptedUsedTime(column: Column, row: EsTask) {
    return fmt_seconds_to_hour_str(Number(row?.acceptUsedTime)) || ''
  }
  
  /* 工单用时 */
  private renderColumnWithTaskUsedTime(column: Column, row: EsTask) {
    return fmt_seconds_to_hour_str(Number(row?.taskUsedTime))  || ''
  }
  
  /* 工作用时 */
  private renderColumnWithWorkUsedTime(column: Column, row: EsTask) {
    return fmt_seconds_to_hour_str(Number(row?.workUsedTime))  || ''
  }
  
  /* 响应用时 */
  private renderColumnWithTaskResponseTime(column: Column, row: EsTask) {
    return fmt_seconds_to_hour_str(Number(row?.taskResponseTime))  || ''
  }
  
  /* 支付方式 */
  private renderColumnWithPaymentMethod(column: Column, row: EsTask) {
    return row?.paymentMethod || ''
  }
  
  /* 非系统字段 */
  private renderColumnWithNotSystem(column: Column, row: EsTask): string | Element {
    // 字段名称
    const fieldName: string = getFieldName(column)
    
    // 自定义字段数据
    if (isArray(row.attribute?.[fieldName])) {
      const value = row?.attribute?.[fieldName] || []
      if (column.formType === 'cascader') return fmt_form_cascader(value, column.setting?.isMulti,  column.setting?.displayMode) || ''
      return concat(value)
    }
    // 审核结算自定义字段
    if (isArray(row.balanceAttribute?.[fieldName])) {
      const value = row?.balanceAttribute?.[fieldName] || []
      return concat(value)
    }

    if(column.formType ==='address') {
      return fmt_form_address(row.attribute?.[fieldName])
    }

    if(column.formType ==='richtext') {
      return fmt_richtext(row.attribute?.[fieldName])
    }

    let commandField = row.attribute?.[fieldName]
    let balanceField = row.balanceAttribute?.[fieldName]
    if (isEmpty(commandField) &&  isEmpty(balanceField)) return ''

    return commandField || balanceField || ''
  }
  
}

export default BizTableTask